<template>
 <div class="date-selector">
  <div class="range-input">

   <div class="input"
        @click.native="selectDate('start')">

    <span class="icon">
     <u-icon name="clock"
             color="#bfc4cc"></u-icon>
    </span>
    <span class="input__text">{{form.start || '请选择日期'}}</span>

   </div>
  </div>

  <u-calendar ref="cal"
              :show="calendar.show"
              :mode="calendar.mode"
              @confirm="calendarChange"
              @close="calendar.show = false"></u-calendar>
 </div>
</template>

<script>
export default {
  name: "DateSelector",
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: [String, Date]
  },
  data() {
    return {
      calendar: {
        mode: 'single',
        show: false,
        target: ''
      },
      form: {
        start: '',
      }
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(new_v) {
        this.$set(this.form, 'start', new_v)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      let cal = this.$refs.cal;
      if (!cal) {
        return;
      }
      // cal.setFormatter((date) => {
      //  return this.formmater(date)
      // })
    })
  },
  methods: {
    calendarChange(e) {
      let [date] = e || [];
      this.$set(this.form, this.calendar.target, date);
      this.calendar.show = false;
      this.submit();
    },
    selectDate(target) {
      this.$set(this.calendar, 'target', target);
      this.calendar.show = true;
    },
    submit() {
      this.$emit('change', this.form.start);
      this.$emit('update:value', this.form.start)
    },
    formmater(format) {
      let {
        date
      } = format;
      let res = this.$m(date).format('YYYY-MM-DD HH:mm:ss');

      return res;
    }
  },
}
</script>

<style lang="scss"
       scoped>
 .date-selector {
  .range-input {
   display: flex;
   flex-direction: row;
   justify-content: center;
   align-items: center;
   color: #bfc4cc;

   .input {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;

    .input__text {
     padding: 0 12rpx;
    }
   }
  }
 }
</style>
